<template>
  <view class="goods-detail-container">
    <!-- 商品标题信息 -->
    <view class="goods-header">
      <view class="goods-title">{{ quotationInfo.product_name }}</view>
      <view class="goods-subtitle">{{ quotationInfo.goods_name }}</view>
      <view class="goods-price">
        <view>价格下浮点数：</view>
        <view class="discount-set">
          <text
            v-for="discount in quotationInfo.general_discount_data"
            class="price-value"
            >厂价
            {{
              quotationInfo.shop_discount == 1
                ? ""
                : "*" + quotationInfo.shop_discount
            }}
            {{
              discount.goods_sku_discount.length !== 0
                ? " * " +
                  discount.goods_sku_discount
                    .map((item) => item.discount)
                    .join("*")
                : ""
            }}({{ discount.discount }})</text
          >
        </view>
      </view>
    </view>

    <!-- 报价表区域 -->
    <view class="price-table-container">
      <image
        :src="canvasImageUrl"
        mode="widthFix"
        class="sku-image"
        webg
        @tap="previewTable"
      ></image>
      <!-- 报价表(Canvas) -->

      <canvas type="2d" id="sku-canvas" @tap="previewTable"></canvas>

      <view class="canvas-loading" v-if="isCanvasLoading">
        <text>正在生成报价表...</text>
      </view>
    </view>
    <view class="getChange"
      ><span class="discount" @click="canvasChange">{{
        "查看折扣图"
      }}</span></view
    >
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { getQuotation, getQuotationDiscount } from "@/apiShop/goods";
// 状态变量
const isCanvasLoading = ref(true);
const canvasImageUrl = ref("");
const isStore = ref(false);
// 表格表头数据
const tableHeaders = ref([]);

// 商品SKU数据 - 模拟图片中的数据
const tableData = ref([]);
const tableHeadersName = ref([]);

// 处理SKU数据的方法
const processSkuData = (skuList) => {
  if (!skuList || !skuList.length) return [];
  // 创建一个Map来存储不同规格的价格
  const specMap = new Map();

  // 遍历SKU数据，按规格分组
  skuList.forEach((sku) => {
    const specs = sku.goods_spec_value_names.split(",");
    const type = specs[0]; // 类型（如：单皮多芯）
    const size = specs[1]; // 规格（如：1.5）

    if (!specMap.has(size)) {
      specMap.set(size, {
        size,
        prices: new Array(tableHeaders.value.length).fill(""),
      });
    }

    // 根据类型找到对应的列索引
    const columnIndex = tableHeaders.value.findIndex(
      (header) => header.name === type
    );

    if (columnIndex !== -1) {
      specMap.get(size).prices[columnIndex] = isStore.value
        ? Number(sku.price_discount)
        : Number(sku.factory_price);
    }
  });

  // 将Map转换为数组格式
  const result = Array.from(specMap.values()).map((item) => ({
    id: item.size,
    values: [item.size, ...item.prices.slice(1)],
  }));

  // 按规格大小排序
  result.sort((a, b) => parseFloat(a.values[0]) - parseFloat(b.values[0]));

  return result;
};
// 绘制Canvas表格
const drawSkuTable = async () => {
  // 检测当前环境
  const systemInfo = uni.getSystemInfoSync();
  try {
    isCanvasLoading.value = true;
    // 确保之前的Canvas资源被释放
    try {
      const query = uni.createSelectorQuery();
      query
        .select("#sku-canvas")
        .fields({ node: true, size: true })
        .exec((res) => {
          if (res && res[0] && res[0].node) {
            const canvas = res[0].node;
            const ctx = canvas.getContext("2d");
            if (ctx) {
              ctx.clearRect(0, 0, canvas.width, canvas.height);
            }
          }
        });
    } catch (e) {
      console.log("清理旧Canvas失败，继续创建新Canvas");
    }

    // 延迟一点再创建Canvas，确保资源释放
    await new Promise((resolve) => setTimeout(resolve, 100));

    const query = uni.createSelectorQuery();
    const canvas = await new Promise((resolve, reject) => {
      query
        .select("#sku-canvas")
        .fields({ node: true, size: true })
        .exec((res) => {
          if (res && res[0] && res[0].node) {
            resolve(res[0].node);
          } else {
            reject(new Error("获取Canvas节点失败"));
          }
        });
    });

    const ctx = canvas.getContext("2d");
    if (!ctx) {
      throw new Error("获取Canvas上下文失败");
    }

    // 获取设备信息
    const systemInfo = uni.getSystemInfoSync();
    const pixelRatio = systemInfo.pixelRatio;
    const screenWidth = systemInfo.screenWidth;
    const isIOS = systemInfo.platform === "ios";

    // iOS设备特别处理
    // 对iOS设备限制像素比和最大尺寸
    const effectivePixelRatio = isIOS ? Math.min(pixelRatio, 1.5) : pixelRatio;

    // iOS设备通常有4096px的最大纹理限制，但我们更保守地设置为2048
    const maxSize = isIOS ? 1800 : 4096;

    // 计算表格实际需要的宽度
    const sidePadding = uni.upx2px(20);

    // 针对iOS，限制表格内容宽度
    const tableContentWidth = isIOS
      ? Math.min(
          tableHeaders.value.reduce((sum, header) => sum + header.width, 0) *
            60,
          maxSize - 2 * sidePadding
        )
      : tableHeaders.value.reduce((sum, header) => sum + header.width, 0) * 100;

    const canvasWidth = Math.min(tableContentWidth + sidePadding * 2, maxSize);

    // 计算实际需要的高度
    const totalRows = tableData.value.length + 1;
    const rowHeight = isIOS ? 25 : 40; // iOS上减小行高
    const totalHeight = 80 + totalRows * rowHeight + 40;
    const canvasHeight = Math.min(totalHeight, maxSize);

    console.log(
      `Canvas尺寸计算: 宽=${canvasWidth}, 高=${canvasHeight}, 平台=${systemInfo.platform}`
    );
    // 限制实际canvas尺寸，避免超过设备限制
    const scaleFactor = Math.min(
      1,
      maxSize / (canvasWidth * effectivePixelRatio),
      maxSize / (canvasHeight * effectivePixelRatio)
    );

    // 设置canvas尺寸 - 对iOS特别处理
    const finalWidth = Math.floor(
      canvasWidth * effectivePixelRatio * scaleFactor
    );
    const finalHeight = Math.floor(
      canvasHeight * effectivePixelRatio * scaleFactor
    );

    console.log(
      `最终Canvas尺寸: ${finalWidth}x${finalHeight}, 缩放因子: ${scaleFactor}`
    );

    // 设置canvas尺寸
    canvas.width = finalWidth;
    canvas.height = finalHeight;

    // 缩放以适应高DPI屏幕
    ctx.scale(
      effectivePixelRatio * scaleFactor,
      effectivePixelRatio * scaleFactor
    );

    // 绘制背景
    ctx.fillStyle = "#FFFFFF";
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);

    // 应用左右边距
    ctx.translate(sidePadding, 0);
    const contentWidth = canvasWidth - sidePadding * 2;

    // 在iOS上，确保字体大小适当
    const baseFontSize = isIOS ? 10 : 14;
    const smallFontSize = isIOS ? 8 : 12;

    if (quotationInfo.value.brand?.text_logo_url) {
      // 绘制品牌Logo背景区域
      const logoAreaHeight = 90; // Logo区域高度
      const logoBackgroundColor =
        quotationInfo.value.brand?.background || "#FFFFFF"; // 获取背景色，默认白色

      // 绘制Logo背景区域（整个canvas宽度）
      ctx.fillStyle = logoBackgroundColor;
      ctx.fillRect(-sidePadding, 0, canvasWidth, logoAreaHeight); // 从边距开始，覆盖整个宽度
      let logoPix = null;
      // 加载品牌Logo图片
      const logoImage = await new Promise((resolve, reject) => {
        const img = canvas.createImage();
        img.onload = () => {
          logoPix = img.width / img.height;
          resolve(img);
        };
        img.onerror = () => reject(new Error("加载Logo失败"));
        img.src = quotationInfo.value.brand?.text_logo_url || "";
      }).catch((err) => {
        console.error("Logo加载失败:", err);
        return null;
      });

      // 绘制品牌Logo（保持居中）
      const centerY = 35; // 稍微调整一下垂直位置以适应背景区域
      const logoWidth = 220;
      const logoHeight = 220 / logoPix;
      const padding = contentWidth / 2 - logoWidth / 2; // 使用内容区域宽度计算居中位置

      if (logoImage) {
        // 绘制Logo
        ctx.drawImage(
          logoImage,
          padding,
          centerY - logoHeight / 2,
          logoWidth,
          logoHeight
        );
      }
    }
    // 绘制产品标题
    ctx.fillStyle = "#333333";
    ctx.font = `bold ${baseFontSize}px sans-serif`;
    ctx.textAlign = "left";
    ctx.textBaseline = "middle";
    ctx.fillText(quotationInfo.value.goods_name, 10, 75);

    // 设置表格参数
    const headerHeight = isIOS ? 25 : 40; // iOS上减小表头高度
    const tableStartY = 90;

    // 计算每列宽度
    const totalWidth = tableHeaders.value.reduce(
      (sum, header) => sum + header.width,
      0
    );
    const columnWidths = tableHeaders.value.map(
      (header) => (header.width / totalWidth) * contentWidth
    );

    // 绘制表格框线
    ctx.strokeStyle = "#CCCCCC";
    ctx.lineWidth = 0.5;

    // 绘制横线
    for (let i = 0; i <= tableData.value.length + 1; i++) {
      const y = tableStartY + i * rowHeight;
      ctx.beginPath();
      ctx.moveTo(0, y);
      ctx.lineTo(contentWidth, y);
      ctx.stroke();
    }

    // 绘制竖线
    let xPos = 0;
    for (let i = 0; i <= columnWidths.length; i++) {
      ctx.beginPath();
      ctx.moveTo(xPos, tableStartY);
      ctx.lineTo(xPos, tableStartY + (tableData.value.length + 1) * rowHeight);
      ctx.stroke();
      if (i < columnWidths.length) {
        xPos += columnWidths[i];
      }
    }

    // 绘制表头文字
    ctx.fillStyle = "#000000";
    ctx.font = `normal bolder ${baseFontSize}px sans-serif`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";

    // 绘制型号和规格文字
    if (tableHeadersName.value && tableHeadersName.value.length >= 2) {
      ctx.beginPath();
      ctx.moveTo(0, tableStartY);
      ctx.lineTo(columnWidths[0], tableStartY + headerHeight);
      ctx.stroke();
      // 绘制第一个标题(规格) - 放在左下角
      ctx.fillText(
        tableHeadersName.value[1], // 索引1在左下角
        columnWidths[0] / 3,
        tableStartY + (headerHeight * 2) / 3
      );

      // 绘制第二个标题(型号) - 放在右上角
      ctx.fillText(
        tableHeadersName.value[0], // 索引0在右上角
        (columnWidths[0] * 2) / 3,
        tableStartY + headerHeight / 3
      );
    } else if (tableHeadersName.value && tableHeadersName.value.length === 1) {
      // 只有一个标题的情况
      ctx.fillText(
        tableHeadersName.value[0],
        columnWidths[0] / 2,
        tableStartY + headerHeight / 2
      );
    }

    // 判断是否为0
    const checkoutZero = (value) =>
      value === undefined || value === null || value == 0;

    // 绘制其它表头
    xPos = columnWidths[0];
    for (let i = 1; i < tableHeaders.value.length; i++) {
      const centerX = xPos + columnWidths[i] / 2;
      ctx.fillText(
        tableHeaders.value[i].name,
        centerX,
        tableStartY + headerHeight / 2
      );
      xPos += columnWidths[i];
    }

    // 绘制数据行
    ctx.font = `normal 500 ${smallFontSize}px sans-serif`;
    for (let rowIndex = 0; rowIndex < tableData.value.length; rowIndex++) {
      const row = tableData.value[rowIndex];
      const y =
        tableStartY + headerHeight + rowIndex * rowHeight + rowHeight / 2;

      xPos = 0;
      for (let colIndex = 0; colIndex < row.values.length; colIndex++) {
        if (colIndex === 0 && row.values[colIndex] === undefined) {
          ctx.beginPath();
          ctx.moveTo(xPos, y - rowHeight / 2); // 左上
          ctx.lineTo(xPos + columnWidths[colIndex], y + rowHeight / 2); // 右下
          ctx.stroke();
          xPos += columnWidths[colIndex];
          continue;
        }
        const centerX = xPos + columnWidths[colIndex] / 2;
        ctx.fillText(
          String(
            checkoutZero(row.values[colIndex]) ? "-" : row.values[colIndex]
          ),
          centerX,
          y
        );
        xPos += columnWidths[colIndex];
      }
    }

    // 在底部绘制日期
    const currentDate = new Date();
    const formattedDate = `${currentDate.getFullYear()}-${String(
      currentDate.getMonth() + 1
    ).padStart(2, "0")}-${String(currentDate.getDate()).padStart(2, "0")}`;

    ctx.font = `bold ${smallFontSize}px sans-serif`;
    ctx.textAlign = "right";
    ctx.fillStyle = "#666666";
    // 在canvas的右下角绘制日期
    ctx.fillText(
      formattedDate,
      contentWidth - 10,
      tableStartY + (tableData.value.length + 1) * rowHeight + 15
    );

    // 确保所有绘制操作已完成
    await new Promise((resolve) => setTimeout(resolve, 200));

    // 将画布转化成图片 - 针对iOS特殊处理
    try {
      const isPCWechat =
        systemInfo.platform === "windows" || systemInfo.platform === "mac";
      const isIOSDevice = systemInfo.platform === "ios";

      // 对于iOS设备，始终使用临时文件方式
      if (isPCWechat || isIOSDevice) {
        // 使用临时文件方式
        console.log("使用临时文件方式生成图片");

        // 在iOS上，确保Canvas已完成渲染
        if (isIOSDevice) {
          await new Promise((resolve) => setTimeout(resolve, 300));
        }

        const tempFilePath = await new Promise((resolve, reject) => {
          uni.canvasToTempFilePath(
            {
              canvas,
              fileType: "jpg",
              quality: isIOSDevice ? 0.6 : 0.8, // iOS降低质量提高成功率
              success: (res) => {
                console.log("临时文件生成成功:", res.tempFilePath);
                resolve(res.tempFilePath);
              },
              fail: (err) => {
                console.error("临时文件生成失败:", err);
                reject(err);
              },
            },
            this
          );
        });

        canvasImageUrl.value = tempFilePath;
      } else {
        // 移动端非iOS尝试使用base64
        console.log("使用base64方式生成图片");
        const base64 = await new Promise((resolve, reject) => {
          uni.canvasToTempFilePath(
            {
              canvas,
              fileType: "jpg",
              quality: 0.9,
              success: (res) => {
                // 读取临时文件并转换为base64
                uni.getFileSystemManager().readFile({
                  filePath: res.tempFilePath,
                  encoding: "base64",
                  success: (data) => {
                    // 转换完成后删除临时文件
                    try {
                      uni.getFileSystemManager().unlink({
                        filePath: res.tempFilePath,
                        fail: () => {},
                      });
                    } catch (e) {}

                    resolve("data:image/jpeg;base64," + data.data);
                  },
                  fail: (err) => reject(err),
                });
              },
              fail: (err) => reject(err),
            },
            this
          );
        });

        canvasImageUrl.value = base64;
      }

      isCanvasLoading.value = false;
    } catch (error) {
      console.error("图片生成失败，尝试备用方法:", error);

      // 任何情况下失败都使用最简单的临时文件方式
      try {
        // 再次确保Canvas已完成渲染
        await new Promise((resolve) => setTimeout(resolve, 500));

        const tempFilePath = await new Promise((resolve, reject) => {
          uni.canvasToTempFilePath(
            {
              canvas,
              fileType: "jpg",
              quality: 0.5, // 降低质量以提高成功率
              success: (res) => {
                console.log("备用方法生成临时文件成功");
                resolve(res.tempFilePath);
              },
              fail: (err) => {
                console.error("备用方法生成临时文件失败:", err);
                reject(err);
              },
            },
            this
          );
        });

        canvasImageUrl.value = tempFilePath;
        isCanvasLoading.value = false;
      } catch (finalError) {
        console.error("所有图片生成方法均失败:", finalError);
        uni.showToast({
          title: "图片生成失败，请重试",
          icon: "none",
        });
        isCanvasLoading.value = false;
      }
    }
  } catch (error) {
    console.error("Canvas绘制失败:", error);
    uni.showToast({
      title: "报价表生成失败，请重试",
      icon: "none",
    });
    isCanvasLoading.value = false;
  }
};

const canvasChange = async () => {
  isStore.value = !isStore.value;
  // 重新画，并计算对应的价钱
  tableData.value = await processSkuData(
    isStore.value
      ? discountInfo.value.goods_sku_discount_data
      : quotationInfo.value.goods_sku_data
  );
  await drawSkuTable();
  await previewTable();
};

// 预览表格图片
const previewTable = () => {
  if (canvasImageUrl.value) {
    // 检查当前图片URL是否为base64格式
    const isBase64 = canvasImageUrl.value.startsWith("data:image");

    // 获取设备信息
    const systemInfo = uni.getSystemInfoSync();
    const isIOS = systemInfo.platform === "ios";

    // 对于iOS设备，需要特殊处理
    if (isIOS) {
      try {
        console.log("iOS设备预览图片");

        // 在预览前确保Canvas已完全渲染
        setTimeout(async () => {
          try {
            // 对于iOS，每次预览前重新生成临时文件
            const query = uni.createSelectorQuery();
            const canvas = await new Promise((resolve, reject) => {
              query
                .select("#sku-canvas")
                .fields({ node: true, size: true })
                .exec((res) => {
                  if (res && res[0] && res[0].node) {
                    resolve(res[0].node);
                  } else {
                    reject(new Error("获取Canvas节点失败"));
                  }
                });
            });

            // 确保Canvas尺寸合适
            if (canvas.width > 2048 || canvas.height > 2048) {
              console.log("Canvas尺寸过大，调整为适合iOS的尺寸");
              // 如果Canvas尺寸过大，可能导致预览问题
              const scaleFactor = Math.min(
                1,
                2048 / canvas.width,
                2048 / canvas.height
              );
              canvas.width = Math.floor(canvas.width * scaleFactor);
              canvas.height = Math.floor(canvas.height * scaleFactor);
            }

            // 使用较低质量生成临时文件，提高成功率
            const tempFilePath = await new Promise((resolve, reject) => {
              uni.canvasToTempFilePath(
                {
                  canvas,
                  fileType: "jpg",
                  quality: 0.7,
                  success: (res) => {
                    console.log("iOS预览：临时文件生成成功", res.tempFilePath);
                    resolve(res.tempFilePath);
                  },
                  fail: (err) => {
                    console.error("iOS预览：临时文件生成失败", err);
                    reject(err);
                  },
                },
                this
              );
            });

            // 使用新生成的临时文件进行预览
            uni.previewImage({
              urls: [tempFilePath],
              current: tempFilePath,
              success: () => {
                console.log("iOS预览成功");
                preViewData();
              },
              fail: (err) => {
                console.error("iOS预览失败", err);
                preViewData();
              },
            });
          } catch (error) {
            console.error("iOS预览准备过程失败:", error);
          }
        }, 200);
      } catch (error) {
        console.error("iOS预览处理失败:", error);
      }
      return;
    }

    // 非iOS设备的处理逻辑
    if (isBase64) {
      try {
        // 尝试使用base64预览
        uni.previewImage({
          urls: [canvasImageUrl.value],
          current: canvasImageUrl.value,
          success: () => {
            console.log("预览成功");
            preViewData();
          },
          fail: async (err) => {
            console.error("预览失败:", err);
            const query = uni.createSelectorQuery();
            const canvas = await new Promise((resolve, reject) => {
              query
                .select("#skuCanvas")
                .fields({ node: true, size: true })
                .exec((res) => {
                  if (res && res[0] && res[0].node) {
                    resolve(res[0].node);
                  } else {
                    reject(new Error("Canvas节点获取失败"));
                  }
                });
            });

            const tempFilePath = await new Promise((resolve, reject) => {
              uni.canvasToTempFilePath(
                {
                  canvas,
                  destWidth: canvas.width,
                  destHeight: canvas.height,
                  fileType: "jpg",
                  quality: 0.8,
                  success: (res) => resolve(res.tempFilePath),
                  fail: (err) => reject(err),
                },
                this
              );
            });

            // 使用临时文件预览
            canvasImageUrl.value = tempFilePath;
            uni.previewImage({
              urls: [tempFilePath],
              current: tempFilePath,
            });
            preViewData();
          },
        });
      } catch (error) {
        console.error("预览失败:", error);
        // uni.showToast({
        //   title: "报价表预览失败，请重试",
        //   icon: "none",
        // });
      }
    } else {
      // 如果已经是临时文件，直接预览
      uni.previewImage({
        urls: [canvasImageUrl.value],
        current: canvasImageUrl.value,
        success: () => {
          console.log("临时文件预览成功");
          preViewData();
        },
        fail: (err) => {
          console.error("临时文件预览失败:", err);
          preViewData();
        },
      });
    }
  } else {
    uni.showToast({
      title: "报价表生成中，请稍候",
      icon: "none",
    });
  }
};

const preViewData = () => {
  setTimeout(async () => {
    isStore.value = false;
    tableData.value = await processSkuData(
      isStore.value
        ? discountInfo.value.goods_sku_discount_data
        : quotationInfo.value.goods_sku_data
    );
    await drawSkuTable();
  }, 500);
};

const quotationInfo = ref({});
const discountInfo = ref({});
const info = ref({});
// 获取报价单信息
const gettableSkuInfo = async () => {
  try {
    const res = await getQuotation({
      goods_id: info.value.id,
      supplier_info_id: info.value.supplier_id,
    });
    // 获取折扣的价格塞进原始的数据中  接口分两个了
    const discount = await getQuotationDiscount({
      goods_id: info.value.id,
      supplier_info_id: info.value.supplier_id,
    });
    discountInfo.value = discount;
    quotationInfo.value = res;

    // 处理SKU数据
    if (
      quotationInfo.value.goods_sku_data &&
      quotationInfo.value.goods_sku_data.length
    ) {
      tableHeadersName.value =
        quotationInfo.value.goods_sku_data[0].goods_spec_name.split(",");
      tableHeaders.value = changeTableHeaders(
        quotationInfo.value.goods_sku_data
      );
      tableData.value = processSkuData(quotationInfo.value.goods_sku_data);
    }
  } catch (error) {
    console.error("获取报价单信息失败:", error);
  }
};
const changeTableHeaders = (data) => {
  let arr = [];
  let name = data[0].goods_spec_name.split(",")[0];
  arr.push({ name: name, width: 1 });
  let sku_nameArr = data.map(
    (item) => item.goods_spec_value_names.split(",")[0]
  );
  let set = new Set([...sku_nameArr]);
  arr = [...arr, ...[...set].map((item) => ({ name: item, width: 1.2 }))];
  return arr;
};
// 页面加载时初始化
onLoad(async (options) => {
  if (options) {
    const { id, supplier_id } = options;
    info.value = {
      id,
      supplier_id,
    };
  }
  await gettableSkuInfo();
  await drawSkuTable();
});
const imageShow = ref(true);
// 在onUnload中彻底清理Canvas
onUnload(() => {
  try {
    console.log("开始清理Canvas资源");
    // 清空所有状态变量
    isCanvasLoading.value = true;
    isStore.value = false;
    tableHeaders.value = [];
    tableData.value = [];
    tableHeadersName.value = [];
    imageShow.value = false;

    // 清理临时图片URL
    if (canvasImageUrl.value) {
      if (canvasImageUrl.value.startsWith("http")) {
        try {
          // 如果是临时文件路径，尝试删除
          uni.getFileSystemManager().unlink({
            filePath: canvasImageUrl.value,
            fail: (err) => {
              console.log("清理临时文件失败", err);
            },
          });
        } catch (e) {
          console.log("尝试删除临时文件出错", e);
        }
      }
      // 无论是否成功删除文件，都清空URL引用
      canvasImageUrl.value = "";
    }

    // 获取Canvas节点并清理
    const query = uni.createSelectorQuery();
    query
      .select("#sku-canvas")
      .fields({ node: true, size: true })
      .exec((res) => {
        if (res && res[0] && res[0].node) {
          const canvas = res[0].node;
          // 重置Canvas尺寸（最小化以释放内存）
          canvas.width = 1;
          canvas.height = 1;
          // 清除画布上下文
          const ctx = canvas.getContext("2d");
          if (ctx) {
            ctx.clearRect(0, 0, 1, 1);
            // 在某些环境中，可以尝试释放WebGL上下文
            if (
              ctx.getContextAttributes &&
              ctx.getContextAttributes().stencil
            ) {
              ctx.getExtension("WEBGL_lose_context")?.loseContext();
            }
          }
          console.log("Canvas清理完成");
        } else {
          console.log("未找到Canvas节点");
        }
      });

    // 清空quotationInfo和discountInfo对象
    if (quotationInfo.value) {
      Object.keys(quotationInfo.value).forEach((key) => {
        quotationInfo.value[key] = null;
      });
    }
    if (discountInfo.value) {
      Object.keys(discountInfo.value).forEach((key) => {
        discountInfo.value[key] = null;
      });
    }

    // 重置info对象
    info.value = { id: null, supplier_id: null };
  } catch (error) {
    console.error("清理Canvas资源时发生错误:", error);
  }
});
</script>

<style lang="scss" scoped>
#sku-canvas {
  // width: auto !important;
  // height: auto !important; // 让高度自适应内容
  // min-height: 1600rpx;
  position: absolute;
  right: 200%;
}
.goods-detail-container {
  min-height: 100vh;

  .goods-header {
    background-color: #ffffff;
    padding: 30rpx;
    border-radius: 10rpx;
    margin-bottom: 20rpx;

    .goods-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      margin-bottom: 15rpx;
    }

    .goods-subtitle {
      font-size: 28rpx;
      color: #666;
      text-align: center;
      margin-bottom: 20rpx;
    }

    .goods-price {
      font-size: 28rpx;
      color: #f7b154;
      text-align: left;
      display: flex;

      .price-value {
        color: #f7b154;
        font-weight: bold;
        white-space: nowrap;
        width: 490rpx;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }

  .price-table-container {
    background-color: #ffffff;
    border-radius: 10rpx;
    position: relative;
    margin-bottom: 20rpx;
    padding: 0;
    overflow-x: auto;

    .sku-image {
      width: 100%;
      display: block;
    }
    .canvas-loading {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: rgba(255, 255, 255, 0.8);
      padding: 20rpx;
      border-radius: 10rpx;
      font-size: 28rpx;
      color: #666;
    }
  }
}
.getChange {
  display: flex;
  /* width: 100%; */
  justify-content: center;
  margin-right: 20rpx;
}
.discount {
  color: #fff;
  font-size: 28rpx;
  border: 1rpx solid #409eff;
  padding: 10rpx;
  background: #409eff;
  border-radius: 10rpx;
}
.discount-set {
  display: flex;
  flex-direction: column;
}
</style>
